package mybatisTest.parsexmltest.jdkdom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class Test {
    public static final File bookxmlf=new File("D:\\code\\javaweb\\Java\\src\\main\\java\\mybatisTest\\parsexmltest\\sax\\book.xml");
    // JAXP 和 DOM
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
        File file=new File("D:\\code\\javaweb\\Java\\src\\main\\java\\mybatisTest\\parsexmltest\\sax\\book.xml");
        DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();
        Document doc = documentBuilder.parse(file);

//        NodeList books =doc.getElementsByTagName("name");//查找所有子孙元素
//        Node name2 = books.item(2);

        //xpath解析
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();
        XPathExpression expr = xPath.compile("//book[id=1]/name/text()");
        String books2=(String)expr.evaluate(doc, XPathConstants.STRING);
        System.out.println(books2);
    }
    @org.junit.Test
    public void testXpath() throws XPathExpressionException, IOException, ParserConfigurationException, SAXException {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse("D:\\code\\javaweb\\Java\\src\\main\\java\\mybatisTest\\parsexmltest\\sax\\xmldemo3.xml");

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr
                = xpath.compile("//book[author='Neal Stephenson']/title/text()");//

        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println(nodes.item(i).getNodeValue());
        }
    }
}
